﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataScripter.Containers;
using DataScripter.Database;
using DataScripter.Database.SqlServer;
using DataScripter.Scripting.InputSources;
using DataScripter.Scripting.Processes.Output;

namespace DataScripter.Scripting.Processes
{
    class TruncateSqlServerTableProcess : BaseProcess
    {
        private ISqlServerInputSource InputSource { get; set; }
        private ITableList TableList { get; set; }

        public TruncateSqlServerTableProcess(string name, IContainer container)
            : base(name, container)
        {
        }

        public override void Initialize(Dictionary<string, string> parameters)
        {
            InputSource = GetTypedParameter<ISqlServerInputSource>(parameters, "SqlServerInputSource");
            TableList = GetTypedParameter<ITableList>(parameters, "TableList");
        }

        public override IProcessOutput Run()
		{
			IDatabaseStructure databaseStructure = Container.Resolve<IDatabaseStructure>();


			IList<ITableStructure> tables = TableList.Select(databaseStructure.GetTable).ToList();

            //IList<IForeignKey> foreignKeysToBeDropped = (from table in tables
            //                                             from foreignKey in table.ForeignKeys
            //                                             let key = foreignKey
            //                                             where tables.Any(t => t.TableName == key.ReferencedTableName)
            //                                             select foreignKey).ToList();

            IList<IForeignKey> foreignKeysToBeDropped = (from table in tables
			                                    from foreignKey in table.ForeignKeysPointingToThisTable
			                                    let key = foreignKey
			                                    where tables.Any(t => t.TableName == key.ReferencedTableName)
			                                    select foreignKey).ToList();

			ISqlServerStatementCreator statementCreator = InputSource.StatementCreator;

            StringBuilder sb=new StringBuilder();

		    foreach (IForeignKey foreignKey in foreignKeysToBeDropped)
		        sb.AppendLine(statementCreator.DropForeignKey(foreignKey));

		    foreach (ITableStructure table in tables)
		        sb.AppendLine(statementCreator.TruncateTable(table));

		    foreach (IForeignKey foreignKey in foreignKeysToBeDropped)
		        sb.AppendLine(statementCreator.CreateForeignKey(foreignKey));

		    TextProcessOutput textProcessOutput = new TextProcessOutput();
		    textProcessOutput.Text = sb.ToString();
			return textProcessOutput;
		}

    }
}
